<template>
    <div class="password">
      <x-header class="header" :left-options="{showBack: showHeaderBack}">修改登录密码</x-header>
      <div class="topHolder"></div>
      <group title="请验证手机号：">
        <x-input title="手机号码" text-align="right" mask="99999999999" v-model="phone" :max="11" placeholder="点击输入"></x-input>
        <x-input title="验证码" v-model="checkCode" :max="6" class="weui-vcode" placeholder="点击输入">
          <x-button slot="right" @click.native="getCheckCode" type="primary" mini :disabled="getCheckCodeStatus" v-text="checkCodeText"> </x-button>
        </x-input>
      </group>
      <group title="请输入新密码(只能包含英文大小写、数字或下划线，长度1-30位)：">
        <x-input type="password" title="输入新密码" text-align="right" v-model="password" :max="30" placeholder="点击输入"></x-input>
        <x-input type="password" title="重复新密码" text-align="right" v-model="password2" :max="30" placeholder="点击输入"></x-input>
      </group>
      <box gap="1rem 0.8rem">
        <x-button type="primary" @click.native="submit" :show-loading="loadingStatus" :disabled="loadingStatus" text="提交修改"></x-button>
      </box>
    </div>
</template>

<script>
  import {getUserInfo,sendCheckCode,changePassword} from '../api'
  import { XHeader , Group, Cell, XInput, Box, XButton  } from 'vux'
  import {message,getLocalStorage,delLocalStorage} from "../common/util";
  import {clearvuex} from "../vuex/clear";

  export default {
    name:'password',
    components:{
      XHeader,
      Group,
      Cell,
      XInput,
      Box,
      XButton
    },
    data () {
      return {
        showHeaderBack:this.GLOBAL.showHeaderBack,
        phone:'',
        checkCode:'',
        getCheckCodeStatus:false,
        checkCodeText:' 获取验证码',
        count:60,
        password:'',
        password2:'',
        loadingStatus:false
      }
    },
    computed:{
      localUserInfo:{
        get () {
          return this.$store.getters.getLocalUserInfo
        },
        set (value) {
          this.$store.commit('updateLocalUserInfo', value)
        }
      },
      checkPhone(){//检查手机号正确性
        const phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/ //正则表达式验证手机号格式
        if (this.phone == '') return '手机号为空'
        if(phoneReg.test(this.phone)) return true
        else return '手机号格式错误'
      },
      checkPassword(){//检查密码正确性
        const passwordReg = /^([A-Z]|[a-z]|[0-9]|[_]){1,30}$/ //判断密码只能包含英文大小写、数字或下划线，长度1-30位
        if (this.password == '' || this.password2 == '') return '密码为空'
        if(passwordReg.test(this.password)){
          if(this.password === this.password2) return true
          else return '两次密码输入不一致'
        }else return '密码格式不正确，只能包含英文大小写、数字或下划线，长度6-30位'
      },
      checkCheckCode(){//检查验证码正确性
        const checkCodeReg = /^[0-9]{4,6}$/ //判断验证码长度正则表达式，4-6位
        if (this.checkCode == '') return '验证码为空'
        if(checkCodeReg.test(this.checkCode)) return true
        else return '验证码格式错误'
      }
    },
    methods:{
      submit(){
        this.loadingStatus = true
        let phoneResult = this.checkPhone
        let passwordResult = this.checkPassword
        let checkCodeResult = this.checkCheckCode
        let reqParams = {
          phone: this.phone,
          checkCode: this.checkCode,
          password: this.password,
          password2: this.password2
        }
        if (!(typeof phoneResult == 'boolean' && phoneResult)){
          message({message: phoneResult,type: 'error'})
          this.loadingStatus = false
        }else{
          if (!(typeof checkCodeResult == 'boolean' && checkCodeResult)){
            message({message: checkCodeResult,type: 'error'})
            this.loadingStatus = false
          }else{
            if (!(typeof passwordResult == 'boolean' && passwordResult)){
              message({message: passwordResult,type: 'error'})
              this.loadingStatus = false
            }else{
              changePassword(reqParams).then((res)=>{
                message({message:res.msg,type:res.status == 'success'?'text':'cancel'})
                if(res.status == 'success'){
                  delLocalStorage('token_stock_index' + sessionStorage.getItem('index'))
                  delLocalStorage('userId_stock_index' + sessionStorage.getItem('index'))
                  clearvuex()
                  this.$router.push({path:'/login'})
                }
                else if(res.status == 'error') console.log('changePassword error info:',res.msg)
                this.loadingStatus = false
              }).catch((err)=>{console.log('changePassword catch info:',err)})
            }
          }
        }
      },
      getCheckCode() {
        let phoneResult = this.checkPhone
        if (!(typeof phoneResult == 'boolean' && phoneResult)){
          message({message:phoneResult,type:'error'})
        }else{
          this.getCheckCodeStatus = true
          sendCheckCode(this.phone).then((res) => {
            //console.log(res)
            this.getCheckCodeStatus = false
            this.countDown()
            if(res.status == 'error') console.log('sendCheckCode error info:',res.msg)
            message({message:res.msg,type:res.status == 'success'?'text':'cancel'})
            this.loadingStatus = false
          }).catch((err)=>{console.log('sendCheckCode catch info:',err)})
        }
      },
      countDown() {
        if (this.count == 0) {
          this.getCheckCodeStatus = false
          this.checkCodeText=" 获取验证码"
          this.count = 60
          return false
        } else {
          this.getCheckCodeStatus = true
          this.checkCodeText=" 重新发送(" + this.count + ")"
          this.count--
        }
        let countDown = this.countDown
        setTimeout(function() {
          countDown();
        },1000);
      }
    },
    mounted(){
      return new Promise((resolve,reject)=>{
        if(getLocalStorage('token_stock_index' + sessionStorage.getItem('index')) && getLocalStorage('userId_stock_index' + sessionStorage.getItem('index')))
          if(JSON.stringify(this.localUserInfo) == '{}')
            getUserInfo().then((res)=>{
              //console.log(res)
              if(res.status == 'success'){
                this.localUserInfo = res.data
                //this.$store.commit('updateLocalUserInfo',res.data)
              }else if(res.status == 'error'){
                console.log('getUserInfo error info:',res.msg)
                message({message:res.msg,type: 'error'})
              }
              resolve()
            }).catch((err)=>{console.log('getUserInfo catch info:',err)})
          else resolve()
        else reject()
      }).then(()=>{
        this.phone = this.localUserInfo.PHONE
        this.loadingStatus = false
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      }).catch(()=>{
        this.loadingStatus = false
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      })
    }
  }
</script>

<style scoped>
  .password{}
</style>
